package com.ittx.dzt.meione.handler;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ittx.dzt.business.PlatformConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.handler.AbstractBasePlatformApiHandler;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.log.monitor.ExceptionLog;
import com.ittx.dzt.meione.util.MeioneSignUtil;
import com.ittx.dzt.mq.core.queue.producer.RocketmqProducer;
import com.ittx.dzt.okhttp.core.HttpRequestTemplate;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.SpringUtil;
import com.ittx.dzt.sys.util.json.JacksonTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 美one平台API处理父类
 * <p>
 *
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/27
 */
@Slf4j
public abstract class AbstractBaseMeioneApiHandler<T> extends AbstractBasePlatformApiHandler<T> {

	@Autowired
	protected RocketmqProducer rocketmqProducer;

	// 取值字段
	public static final String DATA_FIELD = "data";

	/**
	 * 查询总数
	 */
	public static final String RESULT_TOTAL = "total";

	@Override
	public String getPlatformCode() {
		return PlatformConstant.MEIONE;
	}

	/**
	 * 执行API请求通用方法
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 */
	public Result executeApi(StoreConfigDTO storeConfig, Map<String, Object> paramMap, String requestId) {
		long timestamp = System.currentTimeMillis() / 1000;
		//加入公共参数
		paramMap.put("appId", storeConfig.getAppKey());
		paramMap.put("timeStamp", timestamp);
		paramMap.put("v", "1.0");
		paramMap.put("sign_method", "hmac");
		paramMap.put("format", "json");
		// 计算签名
		String signVal = MeioneSignUtil.createSign(paramMap, storeConfig.getAppSecret(), storeConfig.getAppKey());
		// 发起请求
		Result result = null;
		try {
			paramMap.put("sign", signVal);
			result = fetch(storeConfig, paramMap, requestId);
			if (result.isSuccess()) {
				Map<String, Object> resultMap = JacksonTool.toMap(result.getData());
				String codeStr = MapUtil.getStr(resultMap, "code");
				if (!"00000".equals(codeStr)) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getMeioneMethod(), result.getData());
					log.error(msg);
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(JacksonTool.toJson(result));
				}
				return Result.success().addData(resultMap);
			}
			return result;
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getMeioneMethod(), e.getMessage());
			ExceptionLog.error(e, PlatformMessageConstant.MSG_PLAT_0003_MSG, requestId, this.getPlatformCode(), this.getMeioneMethod(), e.getMessage());
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg)).addMsg(msg);
		}
	}

	/**
	 * 公共HTTP请求平台API
	 *
	 * @param storeConfig 店铺配置
	 * @param paramMap    请求参数
	 * @param requestId   请求id
	 * @return 请求结果
	 * @throws IOException
	 */
	private Result<?> fetch(StoreConfigDTO storeConfig, Map<String, Object> paramMap, String requestId) throws IOException {
		String url = storeConfig.getSdkUrl();
		HttpRequestTemplate httpRequestTemplate = SpringUtil.getBean(HttpRequestTemplate.class);
		if (httpRequestTemplate == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0006_MSG, HttpRequestTemplate.class.getName());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0006, msg));
		}
		log.debug("url:{},reqJson:{}", url, paramMap);
		String returnMsg = httpRequestTemplate.postJsonParams(url, JacksonTool.toJson(paramMap), null);
		log.debug("returnMsg:{}", returnMsg);
		if (StrUtil.isEmpty(returnMsg) || !JSONUtil.isTypeJSON(returnMsg)) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0012_MSG, requestId, this.getPlatformCode()
					, this.getMeioneMethod(), url, returnMsg);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0012, msg));
		}
		return Result.success().addData(returnMsg);
	}

	/**
	 * 获取美one平台方法名称
	 *
	 * @return 美one平台API
	 * @date 2022/5/5 15:01
	 */
	public abstract String getMeioneMethod();

	/**
	 * 获取总页数
	 *
	 * @param totalCount 总记录数
	 * @param pageSize   每页显示记录数
	 * @return 总页数
	 */
	public static Integer totalPage(Integer totalCount, Integer pageSize) {
		if (totalCount <= pageSize) {
			return 1;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	public Long totalPage(Long totalCount, Long pageSize) {
		if (totalCount <= pageSize) {
			return 1L;
		}
		if (totalCount % pageSize == 0) {
			return totalCount / pageSize;
		}
		return (totalCount / pageSize) + 1;
	}

	/**
	 * 时间格式转换
	 */
	public String timeToString(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format).withZone(ZoneOffset.UTC);
		return df.format(localDateTime);
	}

	public String format(LocalDateTime localDateTime, String format) {
		DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
		return df.format(localDateTime);
	}
}
